/*
 * Copyright 2019 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.sychip.fhc.app.data.source.local

import androidx.room.Database
import androidx.room.RoomDatabase
import androidx.room.migration.AutoMigrationSpec
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import com.sychip.fhc.app.data.source.dao.BleDeviceDao
import com.sychip.fhc.app.data.source.dao.TBL_BleDevice
import com.sychip.fhc.app.data.source.dao.TBL_WsnRssiHis
import com.sychip.fhc.app.data.source.dao.TBL_WsnTestRecord
import com.sychip.fhc.app.data.source.dao.TaskDao
import com.sychip.fhc.app.data.source.dao.WsnDeviceDao
import com.sychip.fhc.app.data.source.dao.WsnDeviceRssiDao
import com.sychip.fhc.app.data.source.dao.WsnRssiHisDao
import com.sychip.fhc.app.data.source.dao.WsnTestRecordDao
import com.sychip.fhc.app.data.source.entity.BleDeviceEntity
import com.sychip.fhc.app.data.source.entity.TaskEntity
import com.sychip.fhc.app.data.source.entity.WsnDeviceEntity
import com.sychip.fhc.app.data.source.entity.WsnDeviceRssiEntity
import com.sychip.fhc.app.data.source.entity.WsnRssiHisEntity
import com.sychip.fhc.app.data.source.entity.WsnTestRecordEntity
import com.sychip.fhc.app.data.source.local.ToDoDatabase.Companion.LATEST_VERSION
import timber.log.Timber


/**
 * The Room Database that contains the Task table.
 *https://qiita.com/sdkei/items/6acf34f081ddde59ce11
 * Note that exportSchema should be true in production databases.
 */
@Database(
    entities = [TaskEntity::class, BleDeviceEntity::class, WsnDeviceEntity::class, WsnDeviceRssiEntity::class, WsnTestRecordEntity::class, WsnRssiHisEntity::class],
    version = LATEST_VERSION,
    exportSchema = false
)
abstract class ToDoDatabase : RoomDatabase() {
    companion object {
        const val LATEST_VERSION = 5
    }
    abstract fun taskDao(): TaskDao
    abstract fun bleDeviceDao(): BleDeviceDao
    abstract fun wsnDeviceDao(): WsnDeviceDao
    abstract fun wsnDeviceRssiDao(): WsnDeviceRssiDao
    abstract fun wsnTestRecordDao(): WsnTestRecordDao
    abstract fun wsnRssiHisDao(): WsnRssiHisDao

}

val MIGRATION_1_2: Migration = object : Migration(1, 2) {
    override fun migrate(db: SupportSQLiteDatabase) {
        Timber.i("数据库版本 1 升级到 版本 2")
        db.execSQL("""
            CREATE TABLE IF NOT EXISTS `$TBL_WsnTestRecord` (
                `usbId` TEXT not null, 
                `fromTime` TEXT not null,  
                `toTime` TEXT not null default '', 
                `name` TEXT not null default '',
                PRIMARY KEY(`usbId`,`fromTime`)
            )
            """.trimIndent())
    }
}

val MIGRATION_2_3: Migration = object : Migration(2, 3) {
    override fun migrate(db: SupportSQLiteDatabase) {
        Timber.i("数据库版本 2 升级到 版本 3")

        // 1. 创建临时表存储原数据
        db.execSQL("""
            CREATE TABLE IF NOT EXISTS `${TBL_WsnTestRecord}_temp` (
                `usbId` TEXT NOT NULL,
                `fromTime` TEXT NOT NULL,
                `toTime` TEXT NOT NULL DEFAULT '',
                `name` TEXT NOT NULL DEFAULT '',
                `routeName` TEXT NOT NULL DEFAULT '',
                `imageUrl` TEXT NOT NULL DEFAULT '',
                PRIMARY KEY(`usbId`,`fromTime`)
            )
        """.trimIndent())

        // 2. 复制数据到临时表
        db.execSQL("""
            INSERT INTO `${TBL_WsnTestRecord}_temp` 
            (`usbId`, `fromTime`, `toTime`, `name`)
            SELECT `usbId`, `fromTime`, `toTime`, `name`
            FROM `$TBL_WsnTestRecord`
        """.trimIndent())

        // 3. 删除原表
        db.execSQL("DROP TABLE `$TBL_WsnTestRecord`")

        // 4. 创建新表结构
        db.execSQL("""
            CREATE TABLE IF NOT EXISTS `$TBL_WsnTestRecord` (
                `usbId` TEXT NOT NULL,
                `fromTime` TEXT NOT NULL,
                `toTime` TEXT NOT NULL DEFAULT '',
                `projectName` TEXT NOT NULL DEFAULT '',
                `routeName` TEXT NOT NULL DEFAULT '',
                `imageUrl` TEXT NOT NULL DEFAULT '',
                PRIMARY KEY(`usbId`,`fromTime`)
            )
        """.trimIndent())

        // 5. 从临时表复制数据到新表
        db.execSQL("""
            INSERT INTO `$TBL_WsnTestRecord` 
            (`usbId`, `fromTime`, `toTime`, `projectName`, `routeName`, `imageUrl`)
            SELECT `usbId`, `fromTime`, `toTime`, `name`, `routeName`, `imageUrl`
            FROM `${TBL_WsnTestRecord}_temp`
        """.trimIndent())

        // 6. 删除临时表
        db.execSQL("DROP TABLE `${TBL_WsnTestRecord}_temp`")
    }
}

////exportSchema = true,
////autoMigrations =[AutoMigration(from = 2, to = 3,spec = TestAutoMigration::class)] ,
////自动升级 exportSchema必须设置为true(默认为true)
////@RenameColumn(tableName = "user_table", fromColumnName = "job", toColumnName = "user_job")
class TestAutoMigration : AutoMigrationSpec { }


val MIGRATION_3_4: Migration = object : Migration(3, 4) {
    override fun migrate(db: SupportSQLiteDatabase) {
        Timber.i("数据库版本 4 升级到 版本5")
        db.execSQL("ALTER TABLE `$TBL_BleDevice` ADD COLUMN devType TEXT")
    }
}
val MIGRATION_4_5: Migration = object : Migration(4, 5) {
    override fun migrate(db: SupportSQLiteDatabase) {
        Timber.i("数据库版本 4 升级到 版本5")
        db.execSQL("""
            CREATE TABLE IF NOT EXISTS `$TBL_WsnRssiHis` (
                `usbId` TEXT not null, 
                `fullRssi` TEXT not null default '',
                `rssiType` TEXT not null default '',
                `rssiParse` TEXT not null default '',
                `dateTime` TEXT not null,  
                PRIMARY KEY(`usbId`,`fullRssi`,`dateTime`)
            )
            """.trimIndent())
    }
}